package com.zc.items;

import com.badlogic.gdx.scenes.scene2d.Action;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.actions.AlphaAction;
import com.badlogic.gdx.scenes.scene2d.actions.RepeatAction;
import com.badlogic.gdx.scenes.scene2d.actions.SequenceAction;
import com.badlogic.gdx.utils.Array;
import com.zc.actor.ImageTile;
import com.zc.game.Constant;

public class ItemMagnifier extends Item {

	private Array<ImageTile> tempPieces;

	private boolean flag;

	private ImageTile piece;

	public ItemMagnifier() {
		super();
		count = Constant.MAGNIFIER_COUNT;
		banTime = Constant.MAGNIFIER_BAN_TIME;
	}

	@Override
	public void use() {

		count--;
		Constant.MAGNIFIER_COUNT--;

		tempPieces = lm.getRandomArrayPieces(ffc.randomPieceID);

		for (ImageTile tempPiece : tempPieces) {

			flag = false;

			for (ImageTile imagePiece : ffc.imagePieces) {
				if (imagePiece.getFounded() == false) {
					if (tempPiece.getName().equals(imagePiece.getName())) {
						piece = imagePiece;
						flag = true;
						break;
					}
				}
			}
			if (flag) {
				tempPiece.setX(piece.getX() - ffc.shiftX);
				tempPiece.setY(piece.getY() - ffc.shiftY);
				tempPiece.setWidth(piece.getWidth());
				tempPiece.setHeight(piece.getHeight());

				tempPiece.addAction(action());
				piece.addAction(action());
				ffc.stage.addActor(tempPiece);
			}
		}
	}

	@Override
	public void update() {
		super.update();
		if (isFinished) {
			for (ImageTile temp : tempPieces) {
				ffc.stage.getRoot().removeActor(temp);
			}
		}
	}

	public Action action() {

		AlphaAction aa1 = Actions.alpha(0f, Constant.ITEM_MAGNIFIER_DURATION);
		AlphaAction aa2 = Actions.alpha(1f, Constant.ITEM_MAGNIFIER_DURATION);

		SequenceAction sa = Actions.sequence(aa1, aa2);

		RepeatAction ra = Actions.repeat(Constant.ITEM_MAGNIFIER_TIMES, sa);

		Action endAction = Actions.run(new Runnable() {
			@Override
			public void run() {
				isFinished = true;
			}
		});
		SequenceAction sa2 = Actions.sequence(ra, endAction);
		return sa2;
	}
}
